package com.lhy.realm;

import com.lhy.entity.User;
import com.lhy.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;

/**
 * @Author：罗昊宇
 * @Package：com.lhy.realm
 * @Project：shiro-framwork
 * @name：MyRealm
 * @Date：2024/5/8 0008  19:26
 * @Filename：MyRealm
 */
public class MyRealm extends AuthorizingRealm {
    private UserService userService =new UserService();

    @Override
    //授权方法
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("================授权方法===================");
        System.out.println("what's this:"+principals);
        User user = (User) principals.getPrimaryPrincipal();
        //获取登陆者具有的权限
        List<String> list = userService.selectPermissionByName(user.getUsername());
        if (list.size()>0){
            SimpleAuthorizationInfo info =new SimpleAuthorizationInfo();
            info.addStringPermissions(list);
            return info;
        }

        return null;
    }

    @Override
    //认证方法
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("================认证方法===================");
        System.out.println("what's this:"+token);
        String username = (String) token.getPrincipal();
        User user = userService.selectByName(username);
        if (user!=null){
            ByteSource salt=ByteSource.Util.bytes("lhylx");
        AuthenticationInfo info =new SimpleAuthenticationInfo(user,user.getPassword(),salt,this.getName());
        return info;
          }
        return null;
    }
}
